package com.shenyue.nbtownlet.model;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shenyue.nbtownlet.event.BaseListener;

/**
 * Created by 颖杰_2 on 2017-07-08.
 */

public class AddressModel {
    /***获取GPS反地址****/
    public static final String GEOCODE = "http://maps.googleapis.com/maps/api/geocode/json";
    public static final String GEOCODE_ACTION = "$GEOCODE_ACTION$";

    public static void geocode(final Context context, JSONObject param, final BaseListener listener) {
        HttpClientExManager.instance().get(GEOCODE, GEOCODE_ACTION, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                JSONObject data = JSON.parseObject(val);
                JSONArray results = data.getJSONArray("results");
                JSONObject $val = results.getJSONObject(0);
                JSONArray address_components = $val.getJSONArray("address_components");
                StringBuilder sb = new StringBuilder();
                for (int i = 0, j = address_components.size(); i < j; i++) {
                    JSONObject item = address_components.getJSONObject(i);
                    JSONArray types = item.getJSONArray("types");
                    if(types.contains("political") && types.contains("sublocality") && types.contains("sublocality_level_1"))
                        sb.append(item.getString("long_name"));
                }

                for (int i = 0, j = address_components.size(); i < j; i++) {
                    JSONObject item = address_components.getJSONObject(i);
                    JSONArray types = item.getJSONArray("types");
                    if(types.contains("route"))
                        sb.append(item.getString("long_name"));
                }

                if (listener != null)
                    listener.success(val, action);
            }

            @Override
            public void error(String error, String action) {
                if (listener != null)
                    listener.error(error, action);
            }
        });
    }
}
